package com.bp.system.service.impl;

import com.bp.common.annotation.DataScope;
import com.bp.common.constant.UserConstants;
import com.bp.common.core.domain.TreeSelect;
import com.bp.common.exception.BusinessException;
import com.bp.common.utils.StringUtils;
import com.bp.system.domain.SysDept;
import com.bp.system.mapper.SysDeptMapper;
import com.bp.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 * 
 * @author shaominjie
 */
@Service
@Transactional
public class SysDeptServiceImpl implements ISysDeptService {

    private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class);
    @Resource
    private SysDeptMapper deptMapper;

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectById(Long deptId) {
        return deptMapper.selectById(deptId);
    }

    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectList(SysDept dept) {
        return deptMapper.selectList(dept);
    }
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectListWithChild(SysDept dept) {
        return deptMapper.selectListWithChild(dept);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect<Long>> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(this::deptTree).collect(Collectors.toList());
    }
    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<String> selectByRoleId(Long roleId) {
        return deptMapper.selectIdsByRoleId(roleId);
    }
    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteById(Long deptId) {
        return deptMapper.deleteByIdLogic(deptId);
    }
    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildById(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }
    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insert(SysDept dept) {
        SysDept info = deptMapper.selectById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insert(dept);
    }

    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int update(SysDept dept) {
        SysDept newParentDept = deptMapper.selectById(dept.getParentId());
        SysDept oldDept = selectById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.update(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> childrens = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : childrens) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (childrens.size() > 0) {
            deptMapper.updateChildren(childrens);
        }
    }


    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? 1L : dept.getDeptId();
        SysDept info = deptMapper.checkNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && !info.getDeptId().equals(deptId)) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    @Override
    public String importData(List<SysDept> deptList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(deptList) || deptList.size() == 0) {
            throw new BusinessException("导入部门数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int line = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        // 校验导入数据本身是否重复
        Map<Long, Integer> deptIdMap =new HashMap<>(deptList.size());
        Map<String, Integer> deptNameMap =new HashMap<>(deptList.size());

        for (SysDept dept : deptList) {
            if(deptIdMap.containsKey(dept.getDeptId())) {
                deptIdMap.put(dept.getDeptId(),deptIdMap.get(dept.getDeptId())+1);
            } else{
                deptIdMap.put(dept.getDeptId(),0);
            }
            if(deptNameMap.containsKey(dept.getDeptName())) {
                deptNameMap.put(dept.getDeptName(),deptNameMap.get(dept.getDeptName())+1);
            } else{
                deptNameMap.put(dept.getDeptName(),0);
            }
        }
        List<SysDept> deptExists = deptMapper.selectList(new SysDept());
        Map<Long, SysDept> deptExistMap = deptExists.stream().collect(Collectors.toMap(SysDept::getDeptId, s ->s));
        for (SysDept dept : deptList) {
            line ++;
            try {
                StringBuilder failMsgInLine = new StringBuilder();
                // 存在校验
                if(deptExistMap.containsKey(dept.getDeptId()) && !updateSupport) {
                    // 验证与数据库数据的重复,且不更新
                    failMsgInLine.append("部门编号：").append(dept.getDeptId()).append("已存在;");
                } else if(deptIdMap.get(dept.getDeptId())>1) {
                    // 验证导入数据本身重复
                    failMsgInLine.append("部门编号：").append(dept.getDeptId()).append("重复;");
                }


                if(StringUtils.isNotEmpty(failMsgInLine.toString())) {
                    // 验证失败
                    failureNum++;
                    failureMsg.append("<br/>第").append(line).append("行，数据导入失败：").append(failMsgInLine);
                } else{
                    // 验证通过
                    successNum++;
                    SysDept oldDept = deptExistMap.get(dept.getDeptId());
                    if(oldDept!= null){
                        this.update(dept);
                    }else{
                        deptMapper.insert(dept);
                    }
                }
            }
            catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、部门 " + dept.getDeptName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int deleteByIds(Long[] ids) {
        return deptMapper.deleteByIds(ids);
    }
    //<editor-fold desc="私有方法集">
    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext()) {
                    SysDept n =  it.next();
                    recursionFn(list, n);
                }
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<>();
        for (SysDept n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getDeptId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
    private TreeSelect<Long> deptTree(SysDept dept){
        TreeSelect<Long> deptTree = new TreeSelect<>();
        deptTree.setId(dept.getDeptId());
        deptTree.setLabel(dept.getDeptName());
        deptTree.setChildren(dept.getChildren().stream().map(this::deptTree).collect(Collectors.toList()));
        return deptTree;
    }
    //</editor-fold>
}
